package org.cid54.bukkit.model;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author fgo
 */
public class BluePrintDao {

    public static final BluePrintDao instance = new BluePrintDao();

    private BluePrintDao() {
    }

    public void exportBluePrint(BluePrint bluePrint) {

        File dir = new File("blueprints");

        if (!dir.exists()) {
            dir.mkdir();
        }

        File f = new File("blueprints/" + bluePrint.getName() + ".csv");

        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter(f));

            for (BluePrintBlock block : bluePrint.getBlocks()) {

                bw.write(this.marshalLine(block));
                bw.flush();

            }

            bw.close();

        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }

    }

    public BluePrint getBluePrint(String fileName) {

        File dir = new File("blueprints");

        if (!dir.exists()) {
            dir.mkdir();
        }

        BufferedReader br = null;
        try {

            BluePrint bluePrint = new BluePrint();
            bluePrint.setName(fileName);

            File f = new File("blueprints/" + fileName + ".csv");
            br = new BufferedReader(new FileReader(f));

            String line = br.readLine();

            while (line != null) {

                if (!line.startsWith("#")) {
                    bluePrint.getBlocks().add(this.unMarshalLine(line));
                }
                line = br.readLine();

            }

            return bluePrint;

        } catch (IOException ex) {
            //Logger.getLogger(BluePrintDao.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                br.close();
            } catch (IOException ex) {
                //Logger.getLogger(BluePrintDao.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        return null;

    }

    private BluePrintBlock unMarshalLine(String line) {

        String[] pieces = line.split(";");

        BluePrintBlock result = new BluePrintBlock();

        result.setX(Integer.parseInt(pieces[0]));
        result.setZ(Integer.parseInt(pieces[1]));
        result.setY(Integer.parseInt(pieces[2]));
        result.setMatId(Integer.parseInt(pieces[3]));

        return result;

    }

    private String marshalLine(BluePrintBlock block) {

        StringBuilder sb = new StringBuilder();

        sb.append(block.getX()).append(";");
        sb.append(block.getZ()).append(";");
        sb.append(block.getY()).append(";");
        sb.append(block.getMatId()).append("\n");

        return sb.toString();

    }
}
